<?php

require_once("page.class.php");
require_once("functions.php");

class putni_nalozi extends page {
	
	var $db;
	
	function putni_nalozi(){
		$this->db = new db_functions();
		
		$a = getFromInput("a",true);
		$mod = getFromInput("mod",true);
		switch ($a){
			
			
			case "report":
				switch ($mod){
					case "nalog":
						$this->report_nalog();
						break;
					case "gorivo":
						$this->report_gorivo();
						break;
					default:
						$this->report();
						break;
				}
				break;
			case "displayEnter":
				$this->displayEnter();
				break;
			case "updatePrethodnoStanje":
				$this->updatePrethodnoStanje();
				break;
			case "addEnter":
				$this->saveEnter();
				break;
			case "addIssue":
				$this->saveIssue();
				break;
			default:
				$this->displayIssue();
				break;
		}
	}
	
	function displayIssue(){
		$polja = $this->get_Radnici(null,1);
			$this->assign("radnik_id",$polja["polje_id"]);
			$this->assign("radnik_ime",$polja["polje_ime"]);
			$this->assign("radnik_prezime",$polja["polje_prezime"]);
		
		$polja = $this->get_Cars();
			$this->assign("gar",$polja["polje_id"]);
			$this->assign("reg",$polja["polje_ime"]);
			
		echo $this->parseTemplate("putni_nalozi/issue.tpl");
	}
	
	function saveIssue(){
		$broj		= readValFromInput("broj",true);
		$radnik		= getFromInput("radnik",true);
		$relacija	= readValFromInput("relacija",true);
		$regbr		= readValFromInput("regbr",true);
		$garbr		= readValFromInput("garbr",true);
		$datum		= time();
		$napomena	= readValFromInput("napomena",true);
		
		$required = array(
			"broj naloga"	=> $broj,
			"relacija"		=> $relacija,
			"reg.broj"		=> $regbr,
			"gar.broj"		=> $garbr
		);
		
		foreach ($required as $k=>$v){
			if(!strlen($v)){
				die("1{!}Niste popunili polje: $k.\n\nMorate popuniti obavezna polja.");
			}
		}
		
		$ima = $this->db->getOne("SELECT 1 FROM putni_nalozi_izdavanje WHERE broj='$broj' LIMIT 1");
		if ($ima) {
			die("1{!}Putni nalog sa broj $broj je već izdat.");
		}
		
		
		$q = "INSERT INTO putni_nalozi_izdavanje VALUES('', "
			."'".addslashes($broj)."',"
			.$radnik.","
			."'".addslashes($relacija)."',"
			."'".addslashes($regbr)."',"
			."'".addslashes($garbr)."',"
			.$datum.","
			."'".addslashes($napomena)."'"
			.")";
			
		if ($this->db->alterTable($q)) {
			echo "0{!}Nalog izdat.";
		}else{
			echo "1{!}Nalog nije izdat!\n".preg_replace('/<br\s*\/*>/',"\n",mysql_error());
		}
	}
	
	function displayEnter(){
		
		echo $this->parseTemplate("putni_nalozi/enter.tpl");
	}
	
	function updatePrethodnoStanje(){
		$broj = readValFromInput("broj");
		
		$carnum = $this->db->getOne("SELECT reg_broj FROM putni_nalozi_izdavanje WHERE broj='$broj' LIMIT 1");
		$km = "";
		if ($carnum) {
			$q = "SELECT brojilo "
				."FROM putni_nalozi_ulaz pnu, putni_nalozi_izdavanje pni "
				."WHERE pnu.broj=pni.broj "
				."AND pni.reg_broj='$carnum' "
				."ORDER BY vreme_dolazak DESC";
			$km = $this->db->getOne($q);
		}
		echo $km;
	}
	
	function saveEnter(){
		$data = array();
		foreach ($_POST as $k=>$v){
			if (preg_match('/_\d+$/',$k)){
				$base = substr($k,0,strrpos($k,"_"));
				$index = substr($k,strrpos($k,"_")+1);
				
				$v = utf8RawUrlDecode(trim($v));
				$data[$index-1][$base] = utf8RawChrDecode($v);
			}
		}
		
		$broj = readValFromInput("broj",true);
		
		if (!strlen($broj) || preg_match('/[^\d]/',$broj)) {
			die("1{!}Niste uneli broj naloga ili uneti broj nije validan!");
		}
		
		$required = array(
			"datum"			=> "datum",
			"relacija od"	=> "relacija_od",
			"relacija do"	=> "relacija_do",
			"vreme odlaska"	=> "time_out",
			"vreme dolaska"	=> "time_in",
			"pređeno km"	=> "predjeno",
			"stanje brojila"=> "stanje",
		);
		
		$RegExp = array(
			"datum"		=> "/^\d{1,2}\.\d{1,2}\.\d{2,4}$/",
			"time_out"	=> "/^\d{1,2}\s*(:\s*\d{1,2})*$/",
			"time_in"	=> "/^\d{1,2}\s*(:\s*\d{1,2})*$/",
			"predjeno"	=> "/^\d+$/",
			"stanje"	=> "/^\d+$/",
		);
		
		
		foreach ($data as $d){
			
			$date = date2int($d["datum"]);
			
			foreach ($required as $k=>$v){
				if (!strlen($d[$v])) {
					die("1{!}Niste popunili polje: $k.\n\nMorate popuniti obavezna polja.\n".var_export($d[$v],true));
				}else {
					if (isset($RegExp[$v]) && !preg_match($RegExp[$v],$d[$v])) {
						die("1{!}Polje $k nije validno");
					}
				}
				
			}
			
			$q = "SELECT 1 FROM putni_nalozi_izdavanje pni, putni_nalozi_ulaz pnu "
				."WHERE pni.broj=pnu.broj "
				."AND pnu.brojilo=".$d["stanje"]." "
				."AND pnu.broj='".addslashes($broj)."' "
				."LIMIT 1";
			if ($this->db->getOne($q)) {
				die("1{!}Već ste uneli stanje brojila ".$d["stanje"]);
			}
			
			list($hour_out,$minute_out) = explode(":",$d["time_out"]);
			$hour_out = intval($hour_out);
			$minute_out = intval($minute_out);
			$time_out = $date+($hour_out*3600)+($minute_out*60);
			
			list($hour_in,$minute_in) = explode(":",$d["time_in"]);
			$hour_in = intval($hour_in);
			$minute_in = intval($minute_in);
			$time_in = $date+($hour_in*3600)+($minute_in*60);
			
			$queries[] = "INSERT INTO putni_nalozi_ulaz VALUES('',"
						."'".addslashes($broj)."',"
						."'".addslashes($d["relacija_od"])."',"
						."'".addslashes($d["relacija_do"])."',"
						."$time_out,"
						."$time_in,"
						.$d["predjeno"].","
						.$d["stanje"].","
						."'".$d["gorivo_kol"]."',"
						."'".$d["gorivo_iznos"]."',"
						."'".addslashes($d["gorivo_brrac"])."',"
						."'".addslashes($d["tros_opis"])."',"
						."'".$d["tros_iznos"]."',"
						."'".addslashes($d["tros_brrac"])."'"
						.")";
		}
		
		$ret = 0;
		$msg = "Unos izvršen";
		foreach ($queries as $q){
			if (!$this->db->alterTable($q)) {
				$ret=1;
				$msg = $q."\n".mysql_error();
			}
		}
		echo "$ret{!}$msg";
	}
	
	
	/************** REPORTS **************/
	
	function report(){
		$polja = $this->get_Cars();
			$this->assign("garbr",$polja["polje_id"]);
			$this->assign("regbr",$polja["polje_ime"]);
		echo $this->parseTemplate("putni_nalozi/report.tpl");
	}
	
	function report_nalog(){
		
		$broj = readValFromInput("filter_broj",true);
		
		
		$q = "SELECT r.radnik_ime, r.radnik_prezime, pni.* "
			."FROM radnici r, putni_nalozi_izdavanje pni "
			."WHERE r.radnik_id=pni.radnik "
			."AND pni.broj='$broj' ORDER BY datum DESC LIMIT 1";
		$res = $this->db->select2($q);
		if ($res !== false) {
			$res = $res[0];
			
			$this->assign("radnik",$res["radnik_ime"]." ".$res["radnik_prezime"]);
			$this->assign("relacija",$res["relacija"]);
			$this->assign("vozilo",$res["gar_broj"]." - ".$res["reg_broj"]);
			$this->assign("datum",date("d.m.Y H:i",$res["datum"]));
			
			$q = "SELECT * FROM putni_nalozi_ulaz WHERE broj='$broj' ORDER BY vreme_odlazak";
			$res_ulaz = $this->db->select2($q);
			$uvoznji = $ustajanju = $predjkm1 = 0;
			if ($res_ulaz !== false) {
				$date = "";
				$daily = array();
				$daily_key = 0;
				foreach ($res_ulaz as $k=>$row){
					$d = date("d.m.Y",$row["vreme_odlazak"]);
					if ($d != $date) {
						$dates[] = "<tr class=\"dateHead\"><td colspan=\"8\">".$d."</td></tr>";
						$date = $d;
						$daily_key = $k;
					}else{
						$dates[] = "";
					}
					$daily[$daily_key][] = array(
						"date" => $d,
						"km" => $row["km"],
						"out" => $row["vreme_odlazak"],
						"in" => $row["vreme_dolazak"],
						"brojilo" => $row["brojilo"]
					);
					
					$ids[] = $row["id"];
					$rel_od[] = $row["relacija_od"];
					$rel_do[] = $row["relacija_do"];
					$time_out[] = date("H:i",$row["vreme_odlazak"]);
					$time_in[] = date("H:i",$row["vreme_dolazak"]);
					$presao[] = $row["km"];
					$stanje[] = number_format($row["brojilo"],0,",",".");
					$gorivo[] = $row["gorivo_l"]>0?$row["gorivo_l"]." l<br />".number_format($row["gorivo_iznos"],2,",",".")." din.<br />br.rač: ".$row["gorivo_brrac"]:"";
					$other[] = strlen(trim($row["troskovi_opis"]))>0?$row["troskovi_opis"]."<br />".number_format($row["troskovi_iznos"],2,",",".")." din.<br />br.rač: ".$row["troskovi_brrac"]:"";
					
					$predjkm1 += $row["km"];
				}
				
				foreach ($daily as $k=>$day){
					$sum_dates[] = $day[0]["date"];
					$drive = $stay = $km = 0;
					foreach ($day as $m=>$row){
						$drive += $row["in"] - $row["out"];
						$stay += $m>0?$row["out"] - $day[$m-1]["in"]:0;
						$km += $row["km"];
					}
					$sum_km[] = $km;
					$sum_brojilo = $day[count($day)-1]["brojilo"]-$day[0]["brojilo"]+$day[0]["km"];
					$sum_km_brojilo[] = $sum_brojilo!=$km?$sum_brojilo:"";
					$sum_drive[] = sec2time($drive);
					$sum_stay[] = sec2time($stay);
					$sum_drive_sec[] = $drive;
					$sum_stay_sec[] = $stay;
				}
				$this->assign("sum_date",$sum_dates);
				$this->assign("sum_time_drive",$sum_drive);
				$this->assign("sum_time_stay",$sum_stay);
				$this->assign("sum_km",$sum_km);
				$this->assign("sum_km_brojilo",$sum_km_brojilo);
				
				$sum_ukupno_drive = sec2time(array_sum($sum_drive_sec));
				$sum_ukupno_stay = sec2time(array_sum($sum_stay_sec));
				$sum_ukupno_km = array_sum($sum_km);
				$this->assign("sum_ukupno_drive",$sum_ukupno_drive);
				$this->assign("sum_ukupno_stay",$sum_ukupno_stay);
				$this->assign("sum_ukupno_km",$sum_ukupno_km);
				
				$prvakm = $res_ulaz[0]["km"];
				$prvabr = $res_ulaz[0]["brojilo"];
				$zadnjabr = $res_ulaz[count($res_ulaz)-1]["brojilo"];
				$predjkm2 = ($zadnjabr-$prvabr)+$prvakm;
				if ($predjkm2 != $predjkm1) {
					$this->assign("predjenobrojilo"," $predjkm2 km");
				}
				$this->assign("predjenokm",$predjkm1);
				$this->assign("date",$dates);			
				$this->assign("id",$ids);
				$this->assign("relacija_od",$rel_od);
				$this->assign("relacija_do",$rel_do);
				$this->assign("time_out",$time_out);
				$this->assign("time_in",$time_in);
				$this->assign("predjeno",$presao);
				$this->assign("stanje",$stanje);
				$this->assign("gorivo",$gorivo);
				$this->assign("other",$other);
			}else{
				$this->assign("comment_start_nu","<!--");
				$this->assign("comment_end_nu","-->Nalog broj $broj nije ušao.");
			}
			
		}else{
			$this->assign("comment_start_ni","<!--");
			$this->assign("comment_end_ni","-->Nalog broj $broj nije izdat.");
		}
		
		
		echo $this->parseTemplate("putni_nalozi/report_nalozi.tpl");
	}
	function report_gorivo(){
		
		$car = getFromInput("filter_car");
		
		$q = "SELECT pnu.* FROM putni_nalozi_ulaz pnu, putni_nalozi_izdavanje pni WHERE pni.broj=pnu.broj AND gar_broj='$car' AND pnu.gorivo_l>0 ORDER BY vreme_dolazak";
		$res = $this->db->select2($q);
		if ($res !== false) {
			if (count($res)<2) {
				$this->assign("comment_start","<!--");
				$this->assign("comment_end","-->Nema dovoljno zapisa za proračun potrošnje goriva. Potrebno je minimum 2 zapisa.");
			}else{
				for ($i=1; $i<count($res); $i++){
					$start_date[] = int2date($res[$i-1]["vreme_dolazak"]);
					$start_km[] = $res[$i-1]["brojilo"];
					$end_date[] = int2date($res[$i]["vreme_dolazak"]);
					$end_km[] = $res[$i]["brojilo"];
					$diff_km[] = $res[$i]["brojilo"]-$res[$i-1]["brojilo"];
					$gorivo[] = $res[$i-1]["gorivo_l"];
					
					$potrosnja[] = bcdiv(100*$res[$i-1]["gorivo_l"],($res[$i]["brojilo"]-$res[$i-1]["brojilo"]),2);
				}
				$this->assign("datum1",$start_date);
				$this->assign("start_km",$start_km);
				$this->assign("datum2",$end_date);
				$this->assign("end_km",$end_km);
				$this->assign("diff_km",$diff_km);
				$this->assign("gorivo",$gorivo);
				$this->assign("potrosnja",$potrosnja);
			}
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->Nema zapisa.");
		}
			
		echo $this->parseTemplate("putni_nalozi/report_gorivo.tpl");
	}
	
	
	function get_Cars($gar=null){
		$cars = array(
			"01" => "BG 851-506",
			"02" => "BG 851-503",
			"03" => "BG 851-505",
			"04" => "BG 851-504"
		);
		
		
		$gars = array_keys($cars);
		$regs = array_values($cars);
		
		foreach ($gars as $k=>$v){
			if ($v == $gar) {
				$sel[$k] = " selected";
			}else{
				$sel[$k] = "";
			}
		}
		
		$ret = array(
			"polje_id" => $gars,
			"polje_ime"=> $regs,
			"polje_selected" => $sel
		);
		return $ret;
	}
}

?>